package com.company.huisuo.biz.activity

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.company.huisuo.base.BaseActivity
import com.company.huisuo.biz.adapter.CartDataAdapter
import com.company.huisuo.biz.adapter.CartTypeAdapter
import com.company.huisuo.network.api.CategoryApi
import com.company.huisuo.network.api.ProductApi
import com.company.huisuo.biz.bean.CategoryBean
import com.company.huisuo.biz.bean.ProductBean
import com.company.huisuo.biz.dialog.CartPayDialog
import com.company.huisuo.biz.dialog.CartSpecsDialog
import com.company.huisuo.biz.dialog.CartStatsDialog
import com.company.huisuo.network.RetrofitClient
import com.company.huisuo.repository.ProductRepository
import com.company.huisuo.widget.GridSpaceDecoration
import com.company.huisuo.databinding.ActivityCartBinding
import com.lxj.xpopup.XPopup
import kotlinx.coroutines.launch

/**
 * 购物车
 */
class CartActivity : BaseActivity<ActivityCartBinding>() {

    private val mTypeAdapter by lazy {
        CartTypeAdapter { category ->
            // 分类点击事件，根据分类ID加载对应的产品数据
            loadProductDataByCategory(category)
        }
    }
    private val mDataAdapter by lazy {
        CartDataAdapter {
            CartSpecsDialog(this).show()
        }
    }
//    private val mScanSuccessDialog by lazy {
//        XPopup.Builder(this).asCustom(ScanSuccessDialog(this) {
//
//        })
//    }
//    private val mScanPayDialog by lazy {
//        XPopup.Builder(this).asCustom(ScanPayDialog(this) {
//            //支付成功
//            mScanSuccessDialog.show()
//        })
//    }
    private val mPayDialog by lazy {
        XPopup.Builder(this).asCustom(CartPayDialog(this) {
//            mScanPayDialog.show()
        })
    }

    companion object {
        fun start(activity: Activity) {
            activity.startActivity(Intent(activity, CartActivity::class.java))
        }
    }

    override fun initView() {
        mBinding.ivBack.setOnClickListener {
            finish()
        }
        mBinding.tvSettlement.setOnClickListener {
            CartStatsDialog(this) {
                //底部弹窗
                mPayDialog.show()
            }.show()
        }
        mBinding.rcvType.apply {
            layoutManager = LinearLayoutManager(this@CartActivity, RecyclerView.HORIZONTAL, false)
            adapter = mTypeAdapter
        }
        mBinding.rcvData.apply {
            layoutManager = GridLayoutManager(this@CartActivity, 2)
            adapter = mDataAdapter
            addItemDecoration(GridSpaceDecoration(38, 18, 2))
        }
    }

    override fun initData() {
        // 从API接口获取分类数据
        loadCategoryData()
        
        // 从API接口获取产品数据（默认加载第一个分类的产品）
//        loadProductData()
    }

    /**
     * 加载分类数据
     */
    private fun loadCategoryData() {
        lifecycleScope.launch {
            try {
                val productApi = RetrofitClient.createService<ProductApi>()
                val categoryApi = RetrofitClient.createService<CategoryApi>()
                val productRepository = ProductRepository(productApi, categoryApi)
                val result = productRepository.getCategoryList()
                
                if (result.isSuccess) {
                    val categories = result.getOrThrow()
                    if (categories.isNotEmpty()) {
                        // 使用API返回的分类数据
                        mTypeAdapter.submitList(categories)
                        // 默认选择第一个分类并加载对应的产品数据
                        loadProductDataByCategory(categories.first())
                    } else {
                        // 如果API返回空数据，使用本地默认分类数据作为fallback
                        showDefaultCategoryData()
                    }
                } else {
                    // 网络请求失败，使用本地默认分类数据作为fallback
                    showDefaultCategoryData()
                }
            } catch (e: Exception) {
                // 异常处理，使用本地默认分类数据作为fallback
                showDefaultCategoryData()
            }
        }
    }

    /**
     * 加载产品数据
     */
    private fun loadProductData() {
        loadProductDataByCategory(null)
    }

    /**
     * 根据分类ID加载产品数据
     * @param category 分类对象，如果为null则加载所有产品
     */
    private fun loadProductDataByCategory(category: CategoryBean?) {
        lifecycleScope.launch {
            try {
                val productApi = RetrofitClient.createService<ProductApi>()
                val categoryApi = RetrofitClient.createService<CategoryApi>()
                val productRepository = ProductRepository(productApi, categoryApi)
                
                // 根据分类ID筛选产品数据
//                val categoryIds = when (category?.id) {
//                    is Int -> category.id.toString()
//                    is String -> category.id
//                    is Double -> category.id.toInt().toString()
//                    is Float -> category.id.toInt().toString()
//                    else -> null
//                }

              val categoryIds=category?.id;
                val result = productRepository.getProductList(pageNo = 1, pageSize = 20, categoryIds = categoryIds)
                
                if (result.isSuccess) {
                    val productBeans = result.getOrThrow()
                    if (productBeans.isNotEmpty()) {
                        // 使用API返回的数据
                        mDataAdapter.submitList(productBeans)
                    } else {
                        // 如果API返回空数据，使用本地默认数据作为fallback
                        showDefaultData()
                    }
                } else {
                    // 网络请求失败，使用本地默认数据作为fallback
                    showDefaultData()
                }
            } catch (e: Exception) {
                // 异常处理，使用本地默认数据作为fallback
                    showDefaultData()
            }
        }
    }

    /**
     * 显示默认分类数据（网络请求失败时的fallback）
     */
    private fun showDefaultCategoryData() {
        val categoryList = arrayListOf<CategoryBean>()
        categoryList.add(CategoryBean(
            id = "1",
            parentId = 0,
            name = "热销推荐",
            picUrl = ""
        ))

        mTypeAdapter.submitList(categoryList)
        // 默认选择第一个分类并加载对应的产品数据
        loadProductDataByCategory(categoryList.first())
    }

    /**
     * 显示默认数据（网络请求失败时的fallback）
     */
    private fun showDefaultData() {
        val dataList = arrayListOf<ProductBean>()
        dataList.add(ProductBean(
            id = "1",
            name = "酸奶", 
            introduction = "",
            categoryId = "",
            picUrl = "",
            sliderPicUrls = emptyList(),
            specType = false,
            price = 3000, // 30元转换为分
            marketPrice = 3500,
            stock = 100,
            salesCount = 50,
            deliveryTypes = emptyList()
        ))
        dataList.add(ProductBean(
            id = "2",
            name = "苏打水", 
            introduction = "",
            categoryId = "",
            picUrl = "",
            sliderPicUrls = emptyList(),
            specType = false,
            price = 1500, // 15元转换为分
            marketPrice = 1800,
            stock = 100,
            salesCount = 30,
            deliveryTypes = emptyList()
        ))
        dataList.add(ProductBean(
            id = "3",
            name = "脉动", 
            introduction = "",
            categoryId = "",
            picUrl = "",
            sliderPicUrls = emptyList(),
            specType = false,
            price = 1800, // 18元转换为分
            marketPrice = 2000,
            stock = 100,
            salesCount = 40,
            deliveryTypes = emptyList()
        ))
        dataList.add(ProductBean(
            id = "4",
            name = "中分拼盘", 
            introduction = "",
            categoryId = "",
            picUrl = "",
            sliderPicUrls = emptyList(),
            specType = false,
            price = 14800, // 148元转换为分
            marketPrice = 16000,
            stock = 50,
            salesCount = 20,
            deliveryTypes = emptyList()
        ))
        mDataAdapter.submitList(dataList)
    }
}